package org.example.xsda.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import org.example.xsda.common.PageResult;
import org.example.xsda.common.Result;
import org.example.xsda.entity.SysUser;
import org.example.xsda.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @SaCheckRole("admin")
    @GetMapping("/page")
    public Result<PageResult<SysUser>> page(
            @RequestParam(defaultValue = "1") Long current,
            @RequestParam(defaultValue = "10") Long size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Long roleId
    ) {
        PageResult<SysUser> pageResult = userService.page(current, size, keyword, roleId);
        return Result.success(pageResult);
    }

    @SaCheckRole("admin")
    @GetMapping("/{id}")
    public Result<SysUser> getById(@PathVariable Long id) {
        SysUser user = userService.getById(id);
        return Result.success(user);
    }

    @SaCheckRole("admin")
    @PostMapping
    public Result<Void> add(@Validated @RequestBody SysUser user) {
        userService.add(user);
        return Result.success();
    }

    @SaCheckRole("admin")
    @PutMapping
    public Result<Void> update(@Validated @RequestBody SysUser user) {
        userService.update(user);
        return Result.success();
    }

    @SaCheckRole("admin")
    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        userService.delete(id);
        return Result.success();
    }

    @SaCheckRole("admin")
    @PostMapping("/reset-password/{id}")
    public Result<Void> resetPassword(@PathVariable Long id) {
        userService.resetPassword(id);
        return Result.success();
    }
    
    /**
     * 获取当前用户信息（所有角色都可以访问）
     */
    @GetMapping("/profile")
    public Result<SysUser> getProfile() {
        SysUser user = userService.getProfile();
        return Result.success(user);
    }
    
    /**
     * 更新当前用户信息
     */
    @PutMapping("/profile")
    public Result<Void> updateProfile(@RequestBody SysUser user) {
        userService.updateProfile(user);
        return Result.success();
    }
    
    /**
     * 修改密码（首次登录或主动修改）
     */
    @PostMapping("/change-password")
    public Result<Void> changePassword(@RequestBody java.util.Map<String, String> params) {
        String oldPassword = params.get("oldPassword");
        String newPassword = params.get("newPassword");
        userService.changePassword(oldPassword, newPassword);
        return Result.success();
    }
}

